package actor

import (
	"sync"

	sadefine "gitee.com/simplexyz/simplego/actor/define"
	sawork "gitee.com/simplexyz/simplego/actor/work"
)

var (
	gSystem *sadefine.ActorSystem

	gRootPID       *sadefine.PID
	gRootStartedWg *sync.WaitGroup
	gRootStoppedWg *sync.WaitGroup
)

type root struct {
	startedWg   *sync.WaitGroup
	stoppedWg   *sync.WaitGroup
	startedOnce sync.Once
	stoppedOnce sync.Once
}

func createRoot(startedWg *sync.WaitGroup, stoppedWg *sync.WaitGroup) *root {
	r := &root{
		startedWg: startedWg,
		stoppedWg: stoppedWg,
	}
	return r
}

func (r *root) Receive(ctx sadefine.Context) {
	switch msg := ctx.Message().(type) {
	case *sawork.MessagePostWork:
		msg.Work.Execute(ctx)
		sawork.DestroyMessagePostWork(msg)

	case *sawork.MessageDispatchWork:
		msg.Err = msg.Work.Execute(ctx)
		ctx.Respond(msg)

	case *sadefine.Started:
		r.startedOnce.Do(func() {
			r.startedWg.Done()
			r.stoppedWg.Add(1)
		})

	case *sadefine.Stopping:

	case *sadefine.Stopped:
		r.stoppedOnce.Do(func() {
			r.stoppedWg.Done()
		})
	}
}
